package io.github.flylinran.common.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5Util
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Md5Util {
    private static final Object MD5_LOCK = new Object();
    private static MessageDigest md;

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("获取文件MD5失败\n{}", e.getMessage());
        }
    }

    public static String encrypt(String encTxt, String salt) {
        String s = encTxt + salt;
        StringBuilder builder;
        byte[] b;
        synchronized (MD5_LOCK) {
            md.update(s.getBytes());
            b = md.digest();
        }
        builder = new StringBuilder(b.length * 2);
        for (byte aB : b) {
            if (((int) aB & 0xff) < 0x10) {
                builder.append("0");
            }
            builder.append(Long.toHexString((int) aB & 0xff));
        }
        return builder.toString();
    }

}
